package demo01Array;

import org.junit.Test;

import java.util.Arrays;

/**
 * @ClassName $ {NAME}
 * @Description TODO
 * @Author shenxinyuan
 * @Date $ {DATE} $ {TIME}
 * @Version 1. 0
 **/

public class NumberTimesInSortedArray {

    int[] arr = {1, 1, 3, 3, 3, 3, 4, 5};
    //    int []arr = {1,2,3,3,3,3};
//    int []arr = {1,3,3,3,3,4,5};
//    int []arr = {1,2,3,3,3,3};
//    int []arr = {3};
//    int []arr = {3,3,3,3,4,5};
//    int []arr = {1,2,3,3,3,3,4,5};
//    int []arr = {3};
    int K = 4;

    /**
     * @return int 数值K 出现的次数
     * @Author shenxinyuan
     * @Description //TODO思路：寻找左边等于K的下标，寻找右边第一个大于K的下标
     * @Date 17:06 2021/7/17
     * @Param [array, k]
     **/
    public int GetNumberOfK(int[] array, int k) {
        int index = Arrays.binarySearch(array, k);
        if (index < 0) return 0;

        int cnt = 1;
        for (int i = index + 1; i < array.length && array[i] == k; i++)
            cnt++;
        for (int i = index - 1; i >= 0 && array[i] == k; i--)
            cnt++;

        return cnt;
    }

    @Test
    public void test() {
        System.out.println("GetNumberOfK(arr,K) = " + GetNumberOfK(arr, K));
    }
}
